﻿using DoNet.Helper;
using DoNet.Platform.WeiBo;
using DoNet.Platform.WeiBo.Model;

namespace DoNet.OAuth2
{
    /// <summary>
    /// 新浪微博授权登录
    /// https://open.weibo.com/wiki/%E6%8E%88%E6%9D%83%E6%9C%BA%E5%88%B6
    /// </summary>
    public class OAuthWeiBo : OAuthBase
    {
        /// <summary>
        /// 平台
        /// </summary>
        public override OAuthServer Platform
        {
            get
            {
                return OAuthServer.weibo;
            }
        }

        /// <summary>
        /// 获取Authorization Code 的URL
        /// </summary>
        /// <returns></returns>
        public override string GetAuthorizeURL()
        {
            return TokenApi.GetAuthorizeUrl(AppKey, CallbackUrl, "weibo");
        }

        /// <summary>
        /// 获取是否通过授权。
        /// </summary>
        public override bool Authorize()
        {
            if (!string.IsNullOrEmpty(code))
            {
                var result = AccessToken.GetAccessToken(AppKey, AppSecret, code, CallbackUrl);
                if (result != null)
                {
                    if (result.success)
                    {
                        var res = JsonHelper.DeserializeObject<dynamic>(result.data);
                        if (res != null)
                        {
                            token = res.access_token;
                            expiresTime = Convert.ToDateTime(res.expires_time);

                            //授权用户的UID
                            openID = res.uid;

                            if (!string.IsNullOrEmpty(openID))
                            {
                                //获取授权用户信息
                                var res_user = TokenApi.GetUserInfo(token, openID);
                                if (res_user != null)
                                {
                                    if (res_user.success)
                                    {
                                        var userInfo = JsonHelper.DeserializeObject<UserInfo>(res_user.data);
                                        if (userInfo != null)
                                        {
                                            nickName = userInfo.screen_name;
                                            headUrl = userInfo.profile_image_url;
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return false;
        }
    }
}
